#importing system files....
import os
import sys
import subprocess
import optparse
import glob

#importing local files....
import compile_vPath_dissector
import arg_check
import dir_fxns

#-----------------------------------------------------------------------
#This is the main file which gets executed first. First it checks
#whether correct number of arguments are passed or not. If present,
#then it first copies all the code files to the remote machine. Then
#it makes a ssh connection to the remote machine and executes the
#compile_vPath_dissector.py file. At the same time when the execution
#has started on the remote computer, it calls the same file on local
#computer and the compilation task starts. So both the compilations
#are executed simultaneously.

if __name__=="__main__":
    print "program started....."

    #This method call checks that the number of arguments specified
    #are correct or not....  If they are incorrect, then it exits from
    #the program displaying the error message....
    
        
    #retstatus=arg_check.input_check(len(sys.argv))
    
    #if retstatus==-999:       #Checking that the correct number of
                              #arguments are specified.....
    #    exit(1)
    #elif retstatus==0:
    #    path=sys.argv[1]
    #    make_clean_option=sys.argv[2]
        
        #This method call checks that the path specified by user is
        #present on the local system or not....  If it is not there,
        #then it displays an error message and the whole program
        #terminates as its one of the conditions of program....
    
    parser=optparse.OptionParser()
    parser.add_option("-p","--path",
                      dest="path",
                      type="string",
                      help="This takes path of vPth-dissector code directory\
 which is checked out from the vPath-dissector.git repository..",
                      action="store")
    
    parser.add_option("-c","--clean",
                      dest="clean",
                      default=False,
                      help="This flag tells whether you want to do\
 make_dist_clean on the code directory or not. If you specify it, \
then it will do the clean option before compiling the code.",
                      action="store_true")
    
    (options, args)=parser.parse_args()   
    
    path=options.path
    make_clean_option=options.clean 
    
    path_exists=arg_check.path_check(path)
    if path_exists==False:
        print "Wrong path %s specified for local system......" % path
        print "This file runs both local and remote compilation and it\
 has a condition that the path should be there on both local and remote \
system."
        print "Here no path is found on the local system as the argument\
 passed is now incorrect, so the whole program will exit now..."
        exit(1)
    path_exists=arg_check.path_check(path+"/source")
    if path_exists==False:
        print "Source directory not found in the path specified!!!"
        print "Program Terminating..."
        exit(1)
        #Starting the remote execution process.........  First it
        #copies all the files to the remote system and then runs the
        #pyhton command and that filename.....
    list_files=glob.glob("*.py")
    copy_cmd=['scp','-r']+list_files+['rahul@172.20.70.122:/tmp/vPath-dissector-compiler']
    try:
        make_dir=subprocess.Popen(['ssh','rahul@172.20.70.122','mkdir','/tmp/vPath-dissector-compiler'],shell=False,stderr=subprocess.PIPE)
        make_dir.wait()
    except:
        exit(1)
    copy_process=subprocess.Popen(copy_cmd,shell=False)
    copy_process.wait()
    remote_compile_process=-1000
    if copy_process.returncode!=0:
        print "Error occurred while copying files to remote server..... "
        print "Remote compilation will not take place. Please check the \
error. Errorcode: %d" % copy_process.returncode
    else:
        if make_clean_option==True:
            remote_compile_process=subprocess.Popen(['ssh',
            'rahul@172.20.70.122','python',
'/tmp/vPath-dissector-compiler/compile_vPath_dissector.py','-p',path,'-c'],
shell=False)
        else:
            remote_compile_process=subprocess.Popen(['ssh',
            'rahul@172.20.70.122','python',
'/tmp/vPath-dissector-compiler/compile_vPath_dissector.py','-p',path],
shell=False)
        #Starting the execution of program on the local system........
        #At the time of writing of code, it is assumed that the x86
        #system is the local system and x64 is the remote system.  So
        #here we are explicitly passing x86 to tell it was run on a 32
        #bit machine...  If you want to make local as x64,you need to
        #change this value... Otherwise you will get confused....
    status=compile_vPath_dissector.automate_tasks(path,make_clean_option,
                                                      "x86")
    remote_compile_process.wait()
    if remote_compile_process.returncode==0 and status==0:
        local_path=path+"/binaries"
        copy_path="rahul@172.20.70.122:"+local_path+"/vPath-dissector"
        copy_binaries_retcode=subprocess.Popen(['scp','-r',
copy_path,local_path],shell=False)
        copy_binaries_retcode.wait()
        del_dir=subprocess.Popen(['ssh','rahul@172.20.70.122',
'rm','-r',local_path+"/vPath-dissector"],shell=False)
        os.chdir(local_path)
        cp_inst_file=subprocess.Popen(["cp",path+"/install.sh",local_path+"/vPath-dissector"],shell=False)
        cp_inst_file.wait()
        cp_readme_file=subprocess.Popen(["cp",path+"/README",local_path+"/vPath-dissector"],shell=False)
        cp_readme_file.wait()
        tar_process_code=subprocess.Popen(['tar','czf',
'vPath-dissector.tar.gz',"vPath-dissector/"],shell=False)
        tar_process_code.wait()
        del_dir=subprocess.Popen(["rm","-r",
local_path+"/vPath-dissector"],shell=False)
            
        dir_retcode=dir_fxns.mkdir_p(path+"/package") 
                            #Creating a directory inside the binaries
                            #directory with the name as same of the
                            #name of the code directory....
        if dir_retcode!=0:
            print "-------------------------------------------------\
-------------------------"
            print "Error!!!\nUnable to create %s/%s directory!!!"\
 % (path_binaries,code_dir)   #If unable to create directory when it
                              #doesn't exist, then display the error
                              #message....
                
            print "Exiting from the program. First correct the error \
and then re-execute the program......"
            print "--------------------------------------------------\
------------------------"
            exit(1)
            
        tar_file=local_path+"/vPath-dissector.tar.gz"
        dest_path=path+"/package"
        retcode=subprocess.Popen(["mv","-f",
                                    tar_file,dest_path],
                                    shell=False)

        print "DONEEEEEEE......"
    print "You can now close the window...... "

#----------------------------------------------------------------------
